package com.hjxr.quota.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjxr.common.utils.StringUtils;

import java.util.Map;

public class Query<T> {

    public IPage<T> getPage(Map<String, Object> params) {
        return this.getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        //分页参数
        long curPage = 1;
        long limit = 10;

        if (params.get("pageNum") != null) {
            curPage = Long.parseLong((String) params.get("pageNum"));
        }
        if (params.get("pageSize") != null) {
            limit = Long.parseLong((String) params.get("pageSize"));
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);
        //分页参数
        params.put("pageNum", page);
        //排序字段
        //防止SQL注入（因为orderField、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = this.sqlInject((String) params.get("orderField"));
        String order = (String) params.get("order");


        //前端字段排序
        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
            if ("asc".equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }

        //默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }

    /**
     * SQL注入过滤
     *
     * @param str 待验证的字符串
     */
    public String sqlInject(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        //转换成小写
        str = str.toLowerCase();
        //"update"
        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "declare", "alter", "drop"};

        //判断是否包含非法字符
        for (String keyword : keywords) {
            if (str.indexOf(keyword) != -1) {
                return null;
            }
        }

        return str;
    }
}
